import java.sql.SQLOutput;

class MyBlockingQueue{

        private String[] data = null;
        //头节点
        private int head = 0;
        //尾节点
        private int tail = 0;
        //有效元素
        private int size = 0;


        public MyBlockingQueue(int capacity) {
            data = new String[capacity];
        }

        public void put(String ele) throws InterruptedException {
            synchronized (this){
                while (size >= data.length){
                    //队列满了，需要阻塞
                    //return;
                    this.wait();
                }

                data[tail] = ele;
                tail++;
                if (tail >= data.length){
                    tail = 0;
                }
                size++;
                this.notify();
            }

        }

        public String take() throws InterruptedException {
            synchronized (this){
                while (size == 0){
                    //队列空了需要阻塞
                    //return  null;
                    this.wait();
                }

                String tmp = data[head];
                head++;
                if (head >= data.length){
                    head = 0;
                }
                size--;
                this.notify();
                return tmp;
            }

        }
}


 public class Demo3{

    public static void main(String[] args) throws InterruptedException {

        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
            while (true){
                try {
                    myBlockingQueue.put(n + " ");
                    System.out.println("生产元素：" + n);
                    n++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread customer = new Thread(() -> {
            while (true){
                try {
                    String n = myBlockingQueue.take();
                    System.out.println("消耗元素：" + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.start();
        customer.start();
    }
}












